#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include <string>
#include <cstdlib>
#include <cerrno>
#include <cassert>
#include <sys/wait.h>
#include <sys/types.h>
using namespace std;

int main() {
    // 第一步：创建管道
    int pipefd[2] = { 0 };
    int res = pipe(pipefd);
    assert(res == 0);

    // 第二步：创建子进程
    pid_t id = fork();
    if (id < 0) {
        perror("fork");
        return -1;
    }
    if (id == 0) {
        // 子进程
        close(pipefd[0]); // 子进程写，关闭读端
        int cnt = 1;
        while (cnt <= 10000) {
            char buffer[1024];
            snprintf(buffer, sizeof(buffer), "hello father I am your child:%d, my cnt is:%d", getpid(), cnt);
            cnt++;
            // 向管道中写入
            write(pipefd[1], buffer, strlen(buffer));
        }
        exit(0); // 子进程执行完直接退出
    }

    // 父进程
    close(pipefd[1]); // 父进程读，关闭写端
    // 父进程则是一直读
    char messge[1024];
    while (true) {
        int n = read(pipefd[0], messge, sizeof(messge) - 1);
        if (n > 0) {
            messge[n] = '\0';
            cout << "child say: " << messge << " to me" << endl;
            break;
        } else if (n == 0) {
            break;
        }
    }
    // 关闭读端
    close(pipefd[0]);
    
    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    if (rid == id) {
        //cout << "wait child:" << id << "sucess exit signal is:" << (status&0x7F) << endl;
        printf("wait child: %dsucess, exit signal is:%d\n", id, status&0x7F);
    }
    
    return 0;
}